package org.apache.ibatis.lgtest.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author lg
 * @description
 * @create 2019-09-18
 **/
public class NonBlockClient {

  public static void main(String[] args) throws IOException {
    final SocketChannel socketChannel = SocketChannel.open();

    socketChannel.configureBlocking(false);
    socketChannel.connect(new InetSocketAddress("localhost", 12345));

    try {
      Thread.sleep(10000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println(socketChannel.isConnected());
    System.out.println(socketChannel.finishConnect());

    if (socketChannel.isConnected()) {
      ByteBuffer readBuffer = ByteBuffer.allocate(10);
      ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
      new Thread(() -> {
        while (true) {
          int n = -1;
          readBuffer.clear();

          try {
            long start = System.currentTimeMillis();
            n = socketChannel.read(readBuffer);
            long end = System.currentTimeMillis();

          } catch (IOException e) {
            e.printStackTrace();
          }

          if (n > 0) {
            System.out.println("收到服务端消息：" + new String(readBuffer.array(),0,n));
          }

          try {
            Thread.sleep(100);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }).start();

      while (true){
        writeBuffer.clear();
        BufferedReader screenReader = new BufferedReader(new InputStreamReader(System.in));
        String line = screenReader.readLine()+"\n";
        writeBuffer.put(line.getBytes());
        writeBuffer.flip();
        socketChannel.write(writeBuffer);
      }
    }

  }
}
